package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.api.db.QuestionApi;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.RecommendUserApi;
import com.tanhua.api.mongo.UserLikeApi;
import com.tanhua.api.mongo.UserLocationApi;
import com.tanhua.api.mongo.VisitorsApi;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.Visitors;
import com.tanhua.domain.vo.*;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MakeFriendService {

    @Reference
    private RecommendUserApi recommendUserApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private VisitorsApi visitorsApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private QuestionApi questionApi;

    @Reference
    private UserLikeApi userLikeApi;

    @Autowired
    private MessageService messageService;

    @Reference
    private UserLocationApi userLocationApi;

    public ResponseEntity findTodayBest() {
        // 1、根据当前用户id查询推荐用户最高的信息
        RecommendUser recommendUser = recommendUserApi.findMaxScore(UserHolder.getUserId());
        if (recommendUser == null) {
            // 新用户，默认数据
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1L);
            recommendUser.setScore(99D);
        }

        // 2、封装vo
        RecommendUserVo vo = new RecommendUserVo();

        // 获取推荐用户详情
        UserInfo userInfo = userInfoApi.findByUserId(recommendUser.getUserId());
        vo.setUserInfo(userInfo);

        // 缘分值
        vo.setFateValue(recommendUser.getScore().longValue());

        // 3、返回vo
        return ResponseEntity.ok(vo);

    }

    public ResponseEntity recommendation(Integer pageNum, Integer pageSize) {
        // 1、调用api查询推荐列表
        PageBeanVo pageBeanVo = recommendUserApi.findByPage(pageNum, pageSize, UserHolder.getUserId());

        // 2、封装RecommendUserVo
        List<RecommendUserVo> voList = new ArrayList<>();

        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageBeanVo.getItems();
        if (CollectionUtil.isEmpty(recommendUserList)) {
            // 新用户，构造默认数据
            recommendUserList = defaultRecommendUserList();
        }
        for (RecommendUser recommendUser : recommendUserList) {
            RecommendUserVo vo = new RecommendUserVo();
            // 查询推荐用户详情
            UserInfo userInfo = userInfoApi.findByUserId(recommendUser.getUserId());
            vo.setUserInfo(userInfo);
            // 缘分值
            vo.setFateValue(recommendUser.getScore().longValue());

            // 添加到集合中
            voList.add(vo);
        }

        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }

    // 构造推荐用户的默认数据
    private List<RecommendUser> defaultRecommendUserList() {
        List<RecommendUser> list = new ArrayList<>();

        Long[] userIdArray = new Long[]{2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L};

        for (Long userId : userIdArray) {
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(userId);
            recommendUser.setScore(RandomUtil.randomDouble(66, 98));
            list.add(recommendUser);
        }

        return list;
    }

    public ResponseEntity visitors() {
        // 1、获取上次访问时间
        String historyDate = stringRedisTemplate.opsForValue().get("visitors_user_" + UserHolder.getUserId());

        List<VisitorsVo> voList = new ArrayList<>();
        if (StrUtil.isNotEmpty(historyDate)) {
            // 2、老用户，调用api查询历史访客
            List<Visitors> visitorsList = visitorsApi.topVisitors(UserHolder.getUserId(), Long.valueOf(historyDate));
            if (CollectionUtil.isNotEmpty(visitorsList)) {
                for (Visitors visitors : visitorsList) {
                    // 3、封装访客vo
                    VisitorsVo vo = new VisitorsVo();
                    UserInfo userInfo = userInfoApi.findByUserId(visitors.getVisitorUserId());
                    // 用户信息
                    vo.setUserInfo(userInfo);
                    // 缘分值
                    vo.setFateValue(visitors.getScore().longValue());

                    voList.add(vo);
                }
            }
        }

        // 4、记录本次访问时间
        stringRedisTemplate.opsForValue().set("visitors_user_" + UserHolder.getUserId(), System.currentTimeMillis() + "");

        // 5、返回vo集合
        return ResponseEntity.ok(voList);
    }

    public ResponseEntity personalInfo(Long bestUserId) {
        // 1、先查询该用户详情
        UserInfo userInfo = userInfoApi.findByUserId(bestUserId);

        // 2、查询该用户的缘分值
        Long score = recommendUserApi.findbestUserScore(bestUserId, UserHolder.getUserId());

        // 3、封装vo
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfo);
        vo.setFateValue(score);

        // 4、返回vo
        return ResponseEntity.ok(vo);
    }

    public String findQuestionsByUserId(Long userId) {
        Question question = questionApi.findByUserId(userId);

        if (question == null) {
            return "你是喜欢大海，还是高山？";
        }
        return question.getStrangerQuestion();
    }

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    public ResponseEntity replyQuestions(String userId, String reply) {
        Map<String, String> msg = new HashMap<>();
        msg.put("userId", UserHolder.getUserId().toString()); // 登录人用户id
        UserInfo userInfo = userInfoApi.findByUserId(UserHolder.getUserId());
        msg.put("nickname", userInfo.getNickname()); // 登录人用户昵称
        String questions = findQuestionsByUserId(Long.valueOf(userId));
        msg.put("strangerQuestion", questions); // 佳人的陌生人问题
        msg.put("reply", reply); // 登录人回答的问题

        String json = JSON.toJSONString(msg);
        huanXinTemplate.sendMsg(userId, json); // 通过环信，向指定用户发送消息

        return ResponseEntity.ok(null);
    }

    public ResponseEntity findCards() {
        // 1、调用api查询推荐用户前20条
        PageBeanVo pageBeanVo = recommendUserApi.findByPage(1, 20, UserHolder.getUserId());
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageBeanVo.getItems();
        if (CollectionUtil.isEmpty(recommendUserList)) { // 使用默认数据
            recommendUserList = defaultRecommendUserList();
        }

        // 2、封装vo
        List<RecommendUserVo> voList = new ArrayList<>();
        for (RecommendUser recommendUser : recommendUserList) {
            RecommendUserVo vo = new RecommendUserVo();
            // 查询推荐用户详情
            UserInfo userInfo = userInfoApi.findByUserId(recommendUser.getUserId());
            vo.setUserInfo(userInfo);
            // 缘分值
            vo.setFateValue(recommendUser.getScore().longValue());

            // 添加到集合中
            voList.add(vo);
        }
        return ResponseEntity.ok(voList);
    }

    public ResponseEntity likeUser(Long likeUserId) {
        // 1、调用api保存
        userLikeApi.saveUserLike(UserHolder.getUserId(), likeUserId);

        // 2、查询是否为相互喜欢
        if (userLikeApi.isMutualLike(UserHolder.getUserId(), likeUserId)) {
            // 添加好友
            messageService.addContacts(likeUserId);
        }

        return ResponseEntity.ok(null);
    }

    public ResponseEntity unLikeUser(Long likeUserId) {
        // 1、查询双方是否为相互喜欢
        if (userLikeApi.isMutualLike(UserHolder.getUserId(), likeUserId)) {
            // 删除好友关系
        }

        // 2、删除不喜欢记录
        userLikeApi.removeUserLike(UserHolder.getUserId(), likeUserId);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity searchNearUser(String gender, Long distance) {
        // 1、调用api查询附近的人
        List<UserLocationVo> userLocationVoList = userLocationApi.searchNearUser(UserHolder.getUserId(), distance);

        // 2、封装vo
        List<NearUserVo> voList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(userLocationVoList)) {
            for (UserLocationVo userLocation : userLocationVoList) {
                UserInfo userInfo = userInfoApi.findByUserId(userLocation.getUserId());
                // 排除自己
                if (UserHolder.getUserId() == userInfo.getId()) {
                    continue;
                }

                // 排除异性
                if (!gender.equals(userInfo.getGender())) {
                    continue;
                }

                // 封装
                NearUserVo vo = new NearUserVo();
                vo.setUserId(userInfo.getId());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());

                voList.add(vo);

            }
        }

        return ResponseEntity.ok(voList);
    }
}
